package cn.iocoder.yudao.module.chat.dal.redis.history.gpt;

import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.module.chat.controller.app.gpt.vo.ChatMessageVO;
import cn.iocoder.yudao.module.chat.convert.history.gpt.ChatHistoryRedis;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Repository
public class ChatHistoryRedisDao {
    private final String prefix = "USER_";

    @Resource
    private RedisTemplate<String, ChatHistoryRedisDO> redisTemplate;

    public List<ChatMessageVO> searchHistory(ChatMessageVO chatMessageVO){
        return getHistoryList(chatMessageVO);
    }
    public void insertHistory(ChatMessageVO chatMessageVO){
        ChatHistoryRedisDO chatHistoryRedisDO = ChatHistoryRedis.INSTANCE.convert(chatMessageVO);
        redisTemplate.opsForList().leftPush(genKey(chatMessageVO),chatHistoryRedisDO);
    }

    private List<ChatMessageVO> getHistoryList(ChatMessageVO chatMessageVO){
        ListOperations<String, ChatHistoryRedisDO> listListOperations = redisTemplate.opsForList();
        String key = genKey(chatMessageVO);
        Long size = listListOperations.size(key); // 获取List的长度
        if(ObjectUtil.isNull(size) || size == 0){
            return new ArrayList<>();
        }
        return ChatHistoryRedis.INSTANCE.convertList(listListOperations.range(key, 0, size - 1)); // 获取List的所有值
    }

    private String genKey(ChatMessageVO chatMessageVO){
        return chatMessageVO.getTenantId() + CharUtil.DASHED + chatMessageVO.getUserId() + CharUtil.DASHED +chatMessageVO.getSessionId();

    }
}
